package com.znjc.web.controller.device;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysDept;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.StringUtils;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.DeviceCommand;
import com.znjc.device.domain.DeviceCommandLog;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.service.IDeviceCommandLogService;
import com.znjc.device.service.IDeviceCommandService;
import com.znjc.device.service.IIotSerialService;
import com.znjc.device.websocket.WebSocketUsers;
import com.znjc.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【命令下发记录】Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/device/commandLog")
public class DeviceCommandLogController extends BaseController {
    @Autowired
    private IDeviceCommandLogService deviceCommandLogService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IIotSerialService iotSerialService;
    @Autowired
    private IDeviceCommandService deviceCommandService;

    /**
     * 查询命令下发记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceCommandLog deviceCommandLog) {
        startPage();
        LambdaQueryWrapper<DeviceCommandLog> wrapper = getWrapper(deviceCommandLog);
        List<DeviceCommandLog> list = deviceCommandLogService.list(wrapper);
        return getDataTable(packList(list));
    }

    /**
     * 导出命令下发记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:export')")
    @Log(title = "命令下发记录管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceCommandLog deviceCommandLog) {
        LambdaQueryWrapper<DeviceCommandLog> wrapper = getWrapper(deviceCommandLog);
        List<DeviceCommandLog> list = deviceCommandLogService.list(wrapper);
        ExcelUtil<DeviceCommandLog> util = new ExcelUtil<DeviceCommandLog>(DeviceCommandLog.class);
        util.exportExcel(response, packList(list), "命令下发记录管理数据");
    }

    /**
     * 获取命令下发记录管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(deviceCommandLogService.getById(id));
    }

    /**
     * 新增命令下发记录管理
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:add')")
    @Log(title = "命令下发记录管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceCommandLog deviceCommandLog) {
        SysDept dept = deptService.selectDeptById(getDeptId());
        if (CollectionUtils.isEmpty(WebSocketUsers.getUsers()) || !WebSocketUsers.getUsers().keySet().contains(getDeptId() + "")) {
            return error(dept.getDeptName() + "不在线,无法下发指令。");
        }
        boolean flag = deviceCommandLogService.save(deviceCommandLog);
        if (flag) {
            IotSerial serial = iotSerialService.getById(deviceCommandLog.getSerialId());
            List<DeviceCommand> commands = deviceCommandService.listByIds(new ArrayList<>(Arrays.asList(deviceCommandLog.getCommandIds().split(","))));
            if (null != serial && CollectionUtils.isNotEmpty(commands)) {
                commands.stream().forEach(deviceCommand -> {
                    //同步时间命令---确定当前时间
                    if("3".equals(deviceCommand.getCommandType())){
                        deviceCommand.setCommand(deviceCommand.getCommand()+Long.toHexString(System.currentTimeMillis() / 1000));
                    }
                });
                JSONObject json = new JSONObject();
                json.put("serial", serial);
                json.put("commands", commands);
                if (null != dept) {
                    json.put("deptName", dept.getDeptName());
                }
                WebSocketUsers.sendMessageToUserByText(getDeptId() + "", json.toJSONString());
            }
        }
        return toAjax(flag);
    }

    /**
     * 修改命令下发记录管理
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:edit')")
    @Log(title = "命令下发记录管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceCommandLog deviceCommandLog) {
        return toAjax(deviceCommandLogService.updateById(deviceCommandLog));
    }

    /**
     * 删除命令下发记录管理
     */
    @PreAuthorize("@ss.hasPermi('device:commandLog:remove')")
    @Log(title = "命令下发记录管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(deviceCommandLogService.removeByIds(new ArrayList<>(Arrays.asList(ids))));
    }

    /**
     * 查询公共方法
     *
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(DeviceCommandLog entity) {
        LambdaQueryWrapper<DeviceCommandLog> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (null != entity.getSerialId()) {
                wrapper.eq(DeviceCommandLog::getSerialId, entity.getSerialId());
            }
            if (null != entity.getCommandIds()) {
                wrapper.eq(DeviceCommandLog::getCommandIds, entity.getCommandIds());
            }
            if (null != entity.getQueryStartTime() && null != entity.getQueryEndTime()) {
                wrapper.between(DeviceCommandLog::getCreateTime, entity.getQueryStartTime(), entity.getQueryEndTime());
            }
        }
        return wrapper;
    }

    /**
     * 结果封装
     *
     * @param list
     * @return
     */
    private List<DeviceCommandLog> packList(List<DeviceCommandLog> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if (null != entity.getDeptId()) {
                    SysDept dept = deptService.selectDeptById(entity.getDeptId());
                    if (null != dept) {
                        entity.setDeptName(dept.getDeptName());
                    }
                }
                if (null != entity.getSerialId()) {
                    IotSerial serial = iotSerialService.getById(entity.getSerialId());
                    if (null != serial) {
                        entity.setSerialCode(serial.getSerialCode());
                    }
                }
                if (StringUtils.isNotEmpty(entity.getCommandIds())) {
                    List<DeviceCommand> commands = deviceCommandService.listByIds(new ArrayList<>(Arrays.asList(entity.getCommandIds().split(","))));
                    if (CollectionUtils.isNotEmpty(commands)) {
                        StringBuilder s = new StringBuilder();
                        StringBuilder finalS = s;
                        for (DeviceCommand deviceCommand : commands) {
                            s.append(deviceCommand.getName() + ",");
                        }
                        if (StringUtils.isNotEmpty(s)) {
                            s = new StringBuilder(s.toString().substring(0, s.length() - 1));
                        }
                        entity.setCommandNames(s.toString());
                    }
                }
            });
        }
        return list;
    }
}
